/**
 * Copyright (C) 2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package psn.shan.xml.enhancedvalidator.data;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import lombok.extern.slf4j.Slf4j;

import org.jdom2.JDOMException;

/**
 * GenericRelationAccessor <br />
 * 
 * Generic Accessor to manage Relations
 *
 * @author Shan
 *
 */
@Slf4j
public abstract class GenericRelationAccessor<K, T extends Tuple<?>, R extends AbstractBaseRelation<K, T, Map<K, T>>> {

	protected R mRelation = null;

	protected Class<T> mTupleType;

	@SuppressWarnings("unchecked")
	public GenericRelationAccessor(Class<R> aRelationType) {
		try {
			mRelation = aRelationType.newInstance();

			// Bye bye Type Erasure
			mTupleType = (Class<T>) ((ParameterizedType) mRelation.getClass().getGenericSuperclass())
					.getActualTypeArguments()[1];

			log.debug("Creating relation accessor " + mRelation.getRelationName());
			log.debug("Relation type is " + aRelationType);
			log.debug("Tuple type is " + mTupleType);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@PostConstruct
	protected abstract void loadRelation() throws JDOMException, IOException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, SecurityException, CardinalityMismatchException;
	
	public boolean exists(K aKey) {
		return mRelation.hasTuple(aKey);
	}

	/*
	 * Unsafe implementation.
	 * Need to check whether single value map or multi value map.
	 * If single value map, need to create the collection.
	 */
	@SuppressWarnings("unchecked")
	public Collection<T> getValues(K aKey) {
		return (Collection<T>) mRelation.getTuples().get(aKey);
	}

	public List<String> getAttributeNames() {
		return mRelation.getAttributeNames();
	}
}
